package com.voucher.qiege.three;

import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.*;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class PasswordEncryptor {

    // 根据JSESSIONID生成AES参数
    private static Map<String, String> generateKeys(String sessionId) {
        // 原始逻辑：拼接sessionId和固定字符串至32位，全大写
        String material = (sessionId + "abcdefghijklmnopqrstuvwxyz1234567890")
                .substring(0, 32)
                .toUpperCase();
        
        return new HashMap<String, String>() {{
            put("security", "\u4435\u5320\u4d35"); // Unicode前缀
            put("key", material.substring(0, 16));
            put("iv", material.substring(16, 32));
        }};
    }

    // AES加密密码
    public static String encryptPassword(String password, String sessionId) 
            throws GeneralSecurityException {
        Map<String, String> keys = generateKeys(sessionId);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(
            Cipher.ENCRYPT_MODE,
            new SecretKeySpec(keys.get("key").getBytes(StandardCharsets.UTF_8), "AES"),
            new IvParameterSpec(keys.get("iv").getBytes(StandardCharsets.UTF_8))
        );
        byte[] encryptedBytes = cipher.doFinal(password.getBytes(StandardCharsets.UTF_8));
        return keys.get("security") + Base64.getEncoder().encodeToString(encryptedBytes);
    }
}
